﻿using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using Enyim.Caching;
using Ayatta.Contract;
using System.Web.Mvc;
using System.Web.Helpers;
using Ayatta.Contract.Domain;
using Web.Base.Extensions;
using Web.Manage.Controllers;
using Ayatta.Common.Extensions;
using Ayatta.Contract.Component;
using Web.Manage.Areas.Sys.Models;

namespace Web.Manage.Areas.Sys.Controllers
{
    public class SlideController : AdminBaseController
    {
        public SlideController(ILogService logService, IBaseService baseService, IExtraService extraService, IStoreService storeService, IOrderService orderService, IGameService gameService, IAuctionService auctionService, IPassportService passportService, IPaymentService paymentService, IMemcachedClient memcachedClient)
            : base(logService, baseService, extraService, storeService, orderService, gameService, auctionService, passportService, paymentService, memcachedClient)
        {
        }

        public ActionResult Index(int page = 1, int size = 20, string title = null, int? category = null, bool? status = null)
        {
            var model = new SlideControllerModel.Index();
            model.Title = title;
            model.Category = category;
            model.Status = status;
            model.Categories = BaseService.GetPagedSlideCategories(page, size, title, category, status).ToPagedList(page, size);
            return PartialView(model);
        }

        public ActionResult Category(int? param)
        {
            var model = new SlideCategory();
            if (param.HasValue && param.Value > 0)
            {
                model = BaseService.GetSlideCategory(param.Value);
            }
            return PartialView(model);
        }

        [HttpPost]
        public ActionResult Category(int? param, SlideCategory model)
        {
            if (param.HasValue && param.Value > 0)
            {
                var old = BaseService.GetSlideCategory(param.Value);
                if (TryUpdateModel(old))
                {
                    if (!model.Thumb)
                    {
                        old.ThumbH = 0;
                        old.ThumbW = 0;
                    }
                    var result = BaseService.UpdateSlideCategory(old);
                    return result ? Json(HttpStatusCode.OK, "更新成功", true, "/sys/slide") : Json(HttpStatusCode.BadRequest, "更新失败");
                }
            }
            else
            {
                var result = BaseService.CreateSlideCategory(model);
                if (result)
                {
                    return Json(HttpStatusCode.OK, "添加成功", true, "/sys/slide");
                }
            }
            return Json(HttpStatusCode.BadRequest, "失败");
        }

        public ActionResult Slides(int page = 1, int size = 20, int categoryId = 0, string title = null, bool? status = null, DateTime? startTime = null, DateTime? endTime = null)
        {
            var model = new SlideControllerModel.Slides();
            model.Title = title;
            model.CategoryId = categoryId;
            model.Status = status;
            model.StartTime = startTime;
            model.EndTime = endTime;
            model.Categories = BaseService.GetSlideCategories();
            model.List = BaseService.GetPagedSlides(page, size, categoryId, title, status, startTime, endTime).ToPagedList(page, size);
            return PartialView(model);
        }

        public ActionResult Detail(int? param)
        {
            var time = DateTime.Now;
            var model = new SlideControllerModel.Detail();
            var slide = new Slide { StartTime = time, EndTime = time.AddMonths(1) };
            var categories = BaseService.GetSlideCategories();

            if (param.HasValue && param.Value > 0)
            {
                slide = BaseService.GetSlide(param.Value);
                var category = categories.FirstOrDefault(o => o.Id == slide.CategoryId);
                if (category != null)
                {
                    model.Thumb = category.Thumb;
                }
            }
            else
            {
                var category = categories.FirstOrDefault();
                if (category != null)
                {
                    model.Thumb = category.Thumb;
                }
            }
            model.Slide = slide;
            model.Categories = categories;
            return PartialView(model);
        }

        [HttpPost]
        public ActionResult Detail(int? param, Slide model)
        {
            if (param.HasValue && param.Value > 0)
            {
                var old = BaseService.GetSlide(param.Value, true);
                if (TryUpdateModel(old))
                {
                    if (!old.Category.Thumb)
                    {
                        old.Thumb = string.Empty;
                    }
                    var result = BaseService.UpdateSlide(old);
                    return result ? Json(HttpStatusCode.OK, "更新成功", true, "/sys/slide/slides") : Json(HttpStatusCode.BadRequest, "更新失败");
                }
            }
            else
            {
                var c = BaseService.GetSlideCategory(model.CategoryId);
                if (!c.Thumb)
                {
                    model.Thumb = string.Empty;
                }
                var result = BaseService.CreateSlide(model);
                if (result)
                {
                    return Json(HttpStatusCode.OK, "添加成功", true, "/sys/slide/slides");
                }
            }
            return Json(HttpStatusCode.BadRequest, "失败");
        }

        [HttpPost]
        public ActionResult Delete(int? param)
        {
            if (param.HasValue && param.Value > 0)
            {
                var result = BaseService.DeleteSlide(param.Value);
                return result ? Json(HttpStatusCode.OK, "删除成功", false, "/sys/slide/slides") : Json(HttpStatusCode.BadRequest, "删除失败");
            }
            return Json(HttpStatusCode.BadRequest, "失败");
        }

        [HttpPost]
        public ActionResult Upload(int? categoryId, HttpPostedFileBase file)
        {
            var result = new SkResult<string>();
            if (!categoryId.HasValue || categoryId.Value < 0)
            {
                result.Message = "请选择分类！";
                return Json(result);
            }
            if (file != null)
            {
                var extension = Path.GetExtension(file.FileName);
                if (!extension.IsIn(new[] { ".jpeg", ".jpg", ".png", ".gif" }))
                {
                    result.Message = "请选择图片文件！";
                    return Json(result);
                }
                var fileName = Guid.NewGuid().ToString().ToUpper() + extension;
                using (var fileStream = file.InputStream)
                {
                    result = FtpUpload(fileStream, "/slide/" + categoryId.Value + "/", fileName);
                    if (result.Status)
                    {
                        var c = BaseService.GetSlideCategory(categoryId.Value);
                        if (c.Thumb)
                        {
                            var image = new WebImage(file.InputStream).Resize(c.ThumbW, c.ThumbH);

                            using (var stream = new MemoryStream(image.GetBytes()))
                            {
                                var val = FtpUpload(stream, "/slide/" + categoryId.Value + "/thumbnails/", fileName);
                                if (val.Status)
                                {
                                    result.Extra = val.Data;
                                }
                                else
                                {
                                    result.Extra = false;
                                }
                            }
                        }
                    }
                    else
                    {
                        result.Message = "上传图片失败！";
                    }
                }
            }
            else
            {
                result.Message = "请选择正确的文件！";
            }
            return Json(result);
        }
    }
}
